package spring.mymessage.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author ZH
 */
@Component
public class RedisBlockingQueue {
    @Autowired
    private  RedisTemplate<String,String> redisTemplate;
    @Autowired
    private  MyWebSocketServer webSocketServer;
    public static final String PREFIX = "message";

    public  void sendMessageByDept(String deptId){
        new Thread(()->{
            while (true){
                System.out.println("阻塞队列运行了~~~");
                //部门 阻塞方法
                String message = redisTemplate.opsForList().rightPop(PREFIX + "." + deptId, 999, TimeUnit.SECONDS);
                //如果还有的剩 直接全部取出并发信息
                if (redisTemplate.opsForList().size(PREFIX+"."+deptId) != null &&
                        redisTemplate.opsForList().size(PREFIX+"."+deptId) > 0){
                    try {
                        webSocketServer.sendMessageByDeptId("您有"+(redisTemplate.opsForList().size(PREFIX+"."+deptId)+1)+"条消息",deptId);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        redisTemplate.delete(PREFIX + "." + deptId);
                    }
                }else {
                    try {
                        webSocketServer.sendMessageByDeptId(message,deptId);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }).start();
    }
}
